package com.it00zyq.admin.security;

import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.BeanIds;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @Author zyq
 * @Date 2022/4/25 10:47
 * @Description TODO
 * @Version 1.0
 **/
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@RequiredArgsConstructor
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    private final MyUserDetailService detailService;
    private final TokenAuthFilter filter;
    /**
     * 不进行TOKEN验证的URL
     */
    private final static String ERROR_CONTROLLER = "/api/filter/error";
    private final static String LOGIN = "/api/user/login";
    private final static String REGISTER = "/api/user/register";
    private final static String ARTICLE_LIST = "/api/article/list";
    private final static String ARTICLE_DETAIL = "/api/article/detail";
    private final static String ARTICLE_BASE = "/api/article/base";
    private final static String MAIL_SEND = "/api/mail/send";

    @Override
    @Bean(BeanIds.AUTHENTICATION_MANAGER)
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(detailService).passwordEncoder(new NoPasswordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //关闭session管理
        http.csrf().disable().sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and().authorizeRequests().antMatchers(ERROR_CONTROLLER, LOGIN, REGISTER, ARTICLE_LIST, ARTICLE_DETAIL, ARTICLE_BASE, MAIL_SEND).permitAll();
        http.addFilterBefore(filter, UsernamePasswordAuthenticationFilter.class);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {

    }
}
